package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.event.DocumentEvent;
	import com.citytechinc.cmis.client.model.Folder;
	import com.citytechinc.cmis.util.Encoder;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	
	public class DocumentService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://www.cmis.org/2008/05";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        
		private var auth:String;
		
		private var documentCount:int;
		
		private var files:Array;
		
		public function DocumentService(auth:String)
		{
			this.auth = auth;
		}
		
		public function createDocuments(folder:Folder, files:Array):void 
		{
			documentCount = 0;
			this.files = files;
			
			for (var i:int = 0; i < files.length; i++) 
			{
				var file:File = files[i] as File;
	
				var content:String = Encoder.getString(file);
				
				var msg:XML = 
					<entry xmlns="http://www.w3.org/2005/Atom" xmlns:cmis="http://www.cmis.org/2008/05">
						<title>{file.name}</title>
						<content type="application/octet-stream">{content}</content>
						<cmis:object>
							<cmis:properties>
								<cmis:propertyString cmis:name="ObjectTypeId"><cmis:value>document</cmis:value></cmis:propertyString>
							</cmis:properties>
						</cmis:object>
					</entry>
				
				var request:URLRequest = new URLRequest(folder.childrenURL);
	
				request.data = msg;
				request.contentType = "application/atom+xml;type=entry";
				request.method = URLRequestMethod.POST;
				
				var header:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + auth);
	            
	            request.requestHeaders.push(header);
	
				var loader:URLLoader = new URLLoader();
	
				loader.addEventListener(Event.COMPLETE, decrementCount);
				loader.load(request);
			}
			
		}
		
		private function decrementCount(event:Event):void 
		{
			documentCount++
			/*
			var file:File = File(files[documentCount]);
			
			var loader:URLLoader = URLLoader(event.target);
			
			var response:XML = new XML(loader.data);
			
			var link:String = response.link.(@rel=='edit-media').@href;
			
			var request:URLRequest = new URLRequest(link);

			request.method = URLRequestMethod.POST;
			
			var header:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + auth);
			var methodOverride:URLRequestHeader = new URLRequestHeader("X-HTTP-Method-Override", "PUT");
   
            request.requestHeaders.push(header);
            request.requestHeaders.push(methodOverride);
            
            file.upload(request);
			*/
			if (documentCount == files.length)
				this.dispatchEvent(new DocumentEvent(DocumentEvent.CREATED));
		}

	}
	
}